import java.util.PriorityQueue;


public class Day3 {
    public class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
    // 23、合并k个升序链表
    public ListNode mergeKLists1(ListNode[] lists) {
        // 优先级队列——小根堆
        // 把每一个链表的头结点放进入，之后取出堆顶元素就是最小的放入到返回的链表中，也就是尾插
        PriorityQueue<ListNode> heap = new PriorityQueue<>((v1, v2) -> v1.val - v2.val);
        // 把链表中的所有头结点都放入到堆中
        for(ListNode list : lists) {
            if(list != null) {
                heap.offer(list);
            }
        }

        ListNode ret = new ListNode(0);
        ListNode prev = ret;
        while(!heap.isEmpty()) {
            // 不为的空的时候
            ListNode cur = heap.poll();
            prev.next = cur;
            prev = cur;
            if(cur.next != null) {
                heap.offer(cur.next);
            }
        }

        return ret.next;
    }

    public ListNode mergeKLists2(ListNode[] lists) {
        // 递归——分治做法
        return merge(lists,0,lists.length - 1);
    }

    public ListNode merge(ListNode[] lists,int left,int right) {
        if(left > right) {
            return null;
        }
        if(left == right) {
            return lists[left];
        }
        // 1、平分成两个部分
        // [left,mid] [mid+1,right]
        int mid = (left + right) / 2;
        // 2、把左右两个链表分别进行处理
        ListNode l1 = merge(lists,left,mid);
        ListNode l2 = merge(lists,mid + 1,right);
        // 3、合并成两个有序链表
        return mergeTwo(l1,l2);
    }

    public ListNode mergeTwo(ListNode l1,ListNode l2) {
        if(l1 == null) {
            return l2;
        }
        if(l2 == null) {
            return l1;
        }

        ListNode ret = new ListNode(0);
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        ListNode prev = ret;

        while(cur1 != null && cur2 != null) {
            if(cur1.val < cur2.val) {
                prev.next = cur1;
                prev = prev.next;
                cur1 = cur1.next;
            }else {
                prev.next = cur2;
                prev = prev.next;
                cur2 = cur2.next;
            }
        }

        if(cur1 != null) {
            prev.next = cur1;
        }
        if(cur2 != null) {
            prev.next = cur2;
        }
        return ret.next;
    }
}
